//index.js
//获取应用实例
const { regeneratorRuntime, util, api, _, moment } = global;

const app = getApp();

Page({
  data: {
    userInfo: {},
    favoriate:false,
    ticket:false,
    task:false,
    user:false,
    customer:false,
    activity:false,
    scan:false,
    isLogin: false
  },
  async onLoad() {
    // await app.checkLoginStatus()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let user = util.session('user')
    let token = util.session('token')
    if (token) {
      this.setData({
        isLogin: true
      })
    }
    if (user) {
      user = JSON.parse(user)
    }
    this.setData({ userInfo: user  })
    // this.setData({ userInfo: app.globalData.userInfo })
  },
  async wixinTap(e) {
    let { userInfo } = this.data
    let info = e.detail.userInfo
    if (info) {
      userInfo.nickname = info.nickName
      userInfo.coverPic = info.avatarUrl
      userInfo.sex = ['unkown', 'male', 'female'][info.gender]

      let result = await api.system.updateUserInfo(userInfo.id, userInfo)
      if (result === '') {
        util.showMsg('更新成功')
        app.globalData.userInfo = userInfo
        this.setData({ userInfo: userInfo })
      }

    } else {
      util.showMsg("需要通过授权才能继续，请重新点击并授权!")
      return
    }
  },
  getUserInfo() {
    const that=this
     wx.getUserProfile({
     desc: '用于完善用户资料', 
     success: (res) => {
       if (res.errMsg === 'getUserProfile:ok') {
         that.getOpenId(res.userInfo)
       } else {
         util.showMsg('授权后才能登陆哦！')
       }
     }
   })
 },
  // 获取openId
  async getOpenId(user) {
    const res = await api.wxLogin()
    const ret = await api.user.getOpenId(res.code)
    const userInfo = await api.user.judgeUser(ret.data.openid)
    if (userInfo.resultCode === 0) {
      if (userInfo.data) {
        // 已有用户
        let userObj = Object.assign(userInfo.data, user)
        util.session('user', JSON.stringify(userObj))
        this.setData({
          userInfo: userObj
        })
        util.session('openInfo', JSON.stringify(ret.data))
        util.session('token', ret.data.openid)
        app.globalData.token = ret.data.openid
        this.setData({
          isLogin: true
        })
      } else {
        util.session('user', JSON.stringify(user))
        util.session('openInfo', JSON.stringify(ret.data))
        util.session('token', ret.data.openid)
        // 没有用户，进行注册
        wx.navigateTo({
          url: '/pages/authorization/login'
        });
      }
    } else {
      util.showMsg(userInfo.resultMsg)
    }
  },
  goRecord() {
    if (!util.session('token')) {
      return util.showMsg('请先登录')
    }
    wx.navigateTo({
      url: '/pages/own/record'
    });
  },
  goAbout() {
    if (!util.session('token')) {
      return util.showMsg('请先登录')
    }
    wx.navigateTo({
      url: '/pages/own/about'
    })
  }
})
